<template>
	<div class="main_container">
		<div class="head_container">
			<div class="head_left">
				<div class="label">分类名称：</div>
				<el-input v-model="categoryName" placeholder="请输入员工姓名" @input="getList()" style="width: 240px" />
				<div class="label" style="margin-left: 20px">分类类型：</div>
				<el-select v-model="categoryId" class="m-2" placeholder="请选择" size="large" clearable @change="getList()" style="width: 120px">
					<el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
				<div class="search_btn" @click="getList()">查询</div>
			</div>
			<div class="head_right">
				<div class="add_btn dish_btn" @click="addClass('class')">
					<el-icon>
						<Plus />
					</el-icon>
					<span>新增菜品分类</span>
				</div>
				<div class="add_btn" style="margin-left: 20px" @click="addClass('meal')">
					<el-icon>
						<Plus />
					</el-icon>
					<span>新增套餐分类</span>
				</div>
			</div>
		</div>

		<div class="table_box">
			<el-table :data="tableData" border style="width: 100%" size="default" v-if="tableData.length">
				<el-table-column prop="name" label="分类名称" align="center" />
				<el-table-column prop="username" label="分类类型" align="center">
					<template #default="scope">
						<div>
							{{ scope.row.type === 1 ? '菜品分类' : '套餐分类' }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="sort" label="排序" align="center" />
				<el-table-column prop="status" label="状态" align="center">
					<template #default="scope">
						<div class="tableColumn-status" :class="{ stop: String(scope.row.status) === '0' }">
							{{ scope.row.status === 0 ? '禁用' : '启用' }}
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="updateTime" label="操作时间" align="center" />
				<el-table-column prop="status" label="操作" align="center" width="200">
					<template #default="scope">
						<div style="display: flex; justify-content: center; align-items: center;">
							<el-button type="text" style="color: #41b8ff" @click="editHandle(scope.row)">修改</el-button>
							<el-button type="text" size="small" style="color: orange"  @click="deleteHandle(scope.row.id)"> 删除 </el-button>
							<el-button type="text" size="small" :style="{ color: scope.row.status == '1' ? 'red' : '#1dc779' }" @click="statusHandle(scope.row)">{{
								scope.row.status == '1' ? '禁用' : '启用'
							}}</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<Empty v-else :is-search="isSearch" />
		</div>

		<div class="pagin_box">
			<el-pagination
				v-model:current-page="pageParams.page"
				v-model:page-size="pageParams.pageSize"
				:page-sizes="[10, 20, 50, 100]"
				:background="false"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageParams.total"
				@size-change="changeSize"
				@current-change="changePage"
			/>
		</div>

		<el-dialog
			:title="classData.title"
			v-model="classData.dialogVisible"
			width="30%"
			:top="dialogTop"
			style="margin-top: 0px"
			:before-close="handleClose"
		>
			<el-form ref="classRule" :model="classData" class="demo-form-inline" :rules="rules" label-width="100px">
				<el-form-item label="分类名称：" prop="name">
					<el-input v-model="classData.name" placeholder="请输入分类名称" maxlength="20" />
				</el-form-item>
				<el-form-item label="排序：" prop="sort">
					<el-input v-model="classData.sort" placeholder="请输入排序" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="medium" @click="cancel()">取 消</el-button>
				<el-button type="primary" :class="{ continue: actionType === 'add' }" size="medium" @click="submitForm()">确 定</el-button>
				<el-button v-if="action != 'edit'" type="primary" size="medium" @click="submitForm('go')"> 保存并继续添加 </el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { ElPagination, ElMessage, ElMessageBox } from 'element-plus';
import { getCategoryPage,addCategory, editCategory,deleCategory,enableOrDisableEmployee } from '/@/api/category';
import Empty from '/@/components/Empty/index.vue';

let categoryName = ref('');
let categoryId = ref(null);
let tableData = ref([]);
let currentId = ref(null);
let status = ref(null);
let isSearch = ref(false);
let classRule = ref();
let action = ref('');
let type = ref('');
let actionType = ref('');
const dialogTop = ref('30px');
let typeOptions = [
	{
		label: '菜品分类',
		value: 1,
	},
	{
		label: '套餐分类',
		value: 2,
	},
];
let pageParams = ref({
	page: 1,
	pageSize: 10,
	total: 0,
});
let classData = ref<any>({
	title: '',
	dialogVisible: false,
	name: '',
	sort: '',
});
const rules = {
	name: [
		{
			required: true,
			trigger: 'blur',
			validator: (rule: any, value: string, callback: Function) => {
				var reg = new RegExp('^[A-Za-z\u4e00-\u9fa5]+$');
				if (!value) {
					callback(new Error(classData.value.title + '不能为空'));
				} else if (value.length < 2) {
					callback(new Error('分类名称输入不符，请输入2-20个字符'));
				} else if (!reg.test(value)) {
					callback(new Error('分类名称包含特殊字符'));
				} else {
					callback();
				}
			},
		},
	],
	sort: [
		{
			required: true,
			trigger: 'blur',
			validator: (rule: any, value: string, callback: Function) => {
				if (value || String(value) === '0') {
					const reg = /^\d+$/;
					if (!reg.test(value)) {
						callback(new Error('排序只能输入数字类型'));
					} else if (Number(value) > 99) {
						callback(new Error('排序只能输入0-99数字'));
					} else {
						callback();
					}
				} else {
					callback(new Error('排序不能为空'));
				}
			},
		},
	],
};

onMounted(() => {
	getList();
});

//删除
const deleteHandle = async (id:string) => {
	ElMessageBox.confirm('确认删除此分类?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		deleCategory(id)
			.then((res) => {
				if (res.code === 1) {
					ElMessage.success('删除成功！');
					getList();
				}else{
					ElMessage.success(res.msg);
				}
			})
			.catch((err) => {
				ElMessage.error('请求出错了：' + err.message);
			});
	});
};

//修改状态
const statusHandle = (row: any) => {
	if (row.username === 'admin') {
		ElMessage.error('管理员账号不能修改状态');
		return;
	}
	currentId.value = row.id;
	status.value = row.status;
	ElMessageBox.confirm('确认调整该账号的状态?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		enableOrDisableEmployee({ id: currentId.value, status: !status.value ? 1 : 0 })
			.then((res) => {
				if (res.code === 1) {
					ElMessage.success('账号状态更改成功！');
					getList();
				}
			})
			.catch((err) => {
				ElMessage.error('请求出错了：' + err.message);
			});
	});
};

//新增
const addClass = (st: any) => {
	if (st == 'class') {
		classData.value.title = '新增菜品分类';
		type.value = '1';
	} else {
		classData.value.title = '新增套餐分类';
		type.value = '2';
	}
	action.value = 'add';
	classData.value.name = '';
	classData.value.sort = '';
	classData.value.dialogVisible = true;
	actionType.value = 'add';
};

// 修改
const editHandle = (val: any) => {
	classData.value.title = '修改分类';
	action.value = 'edit';
	classData.value.name = val.name;
	classData.value.sort = val.sort;
	classData.value.id = val.id;
	classData.value.dialogVisible = true;
	actionType.value = 'edit';
};

//取消
const cancel = () => {
	classData.value.dialogVisible = false;
	classRule.value.resetFields();
};

// 关闭弹框
const handleClose = () => {
	classData.value.dialogVisible = false;
	//对该表单项进行重置，将其值重置为初始值并移除校验结果
	classRule.value.resetFields();
};

//数据提交
const submitForm = (st?: string) => {
	if (action.value === 'add') {
		classRule.value.validate((value: boolean) => {
			if (value) {
				addCategory({
					name: classData.value.name,
					type: type.value,
					sort: classData.value.sort,
				})
					.then((res) => {
						if (res.code === 1) {
							ElMessage.success('分类添加成功！');
							classRule.value.resetFields();
							if (!st) {
								classData.value.dialogVisible = false;
							}
							getList();
						} else {
							ElMessage.error(res.desc || res.msg);
						}
					})
					.catch((err) => {
						ElMessage.error('请求出错了：' + err.message);
					});
			}
		});
	} else {
		classRule.value.validate((value: boolean) => {
			if (value) {
				editCategory({
					id: classData.value.id,
					name: classData.value.name,
					sort: classData.value.sort,
				})
					.then((res) => {
						if (res.code === 1) {
							ElMessage.success('分类修改成功！');
							classData.value.dialogVisible = false;
							classRule.value.resetFields();
							getList();
						} else {
							ElMessage.error(res.desc || res.msg);
						}
					})
					.catch((err) => {
						ElMessage.error('请求出错了：' + err.message);
					});
			}
		});
	}
};

//获取列表数据
const getList = async () => {
	let req = {
		page: pageParams.value.page,
		pageSize: pageParams.value.pageSize,
		name: categoryName.value,
		type: categoryId.value
	};
	const res = await getCategoryPage(req);
	if (res.code == 1) {
		tableData.value = res.data.records;
		pageParams.value.total = res.data.total;
	} else {
		tableData.value = [];
		pageParams.value.total = 0;
	}
};

//每页条数
const changeSize = (size: number) => {
	pageParams.value.pageSize = size;
	getList();
};

//翻页
const changePage = (page: number) => {
	pageParams.value.page = page;
	getList();
};
</script>
<style lang="scss" scoped>
@import url('./src/css/category.scss');
</style>
